/**
 * HTTP工具库使用示例
 * 展示各种使用场景和配置方法
 */

import http, { HttpRequest } from '../api/http'

// ========== 基础使用示例 ==========

// 1. GET请求
export const exampleGet = async () => {
    try {
        const result = await http.get('/user/info', { id: 123 })
        console.log('用户信息:', result)
        return result
    } catch (error) {
        console.error('获取用户信息失败:', error)
    }
}

// 2. POST请求
export const examplePost = async () => {
    try {
        const userData = {
            name: '张三',
            email: 'zhangsan@example.com',
            age: 25
        }
        const result = await http.post('/user/create', userData)
        console.log('创建用户成功:', result)
        return result
    } catch (error) {
        console.error('创建用户失败:', error)
    }
}

// ========== 自定义Header示例 ==========

// 3. 带自定义header的请求
export const exampleCustomHeader = async () => {
    try {
        const result = await http.get('/protected/data', {}, {
            header: {
                'Authorization': 'Bearer your-jwt-token',
                'X-Custom-Header': 'custom-value'
            }
        })
        return result
    } catch (error) {
        console.error('请求失败:', error)
    }
}

// 4. 覆盖默认Content-Type
export const exampleFormData = async () => {
    try {
        const formData = {
            username: 'admin',
            password: '123456'
        }
        const result = await http.post('/login', formData, {
            header: {
                'Content-Type': 'application/x-www-form-urlencoded'
            }
        })
        return result
    } catch (error) {
        console.error('登录失败:', error)
    }
}

// ========== 文件上传示例 ==========

// 5. 文件上传
export const exampleFileUpload = async (filePath) => {
    try {
        // 注意：实际的文件上传需要使用uni.uploadFile
        // 这里只是展示如何配置multipart/form-data
        const result = await http.post('/upload', {
            file: filePath,
            description: '文件描述'
        }, {
            header: {
                'Content-Type': 'multipart/form-data'
            }
        })
        return result
    } catch (error) {
        console.error('文件上传失败:', error)
    }
}

// ========== 创建自定义HTTP实例 ==========

// 6. 创建专用的API实例
export const createCustomHttpInstance = () => {
    const customHttp = new HttpRequest({
        baseURL: 'https://api.example.com/v2',
        timeout: 15000,
        header: {
            'Content-Type': 'application/json',
            'X-API-Version': '2.0'
        }
    })

    // 添加自定义请求拦截器
    customHttp.addRequestInterceptor(
        (config) => {
            // 添加时间戳
            config.header['X-Timestamp'] = Date.now().toString()
            return config
        }
    )

    // 添加自定义响应拦截器
    customHttp.addResponseInterceptor(
        (response) => {
            // 自定义业务逻辑处理
            if (response.data && response.data.status === 'success') {
                return response.data.result
            }
            throw new Error(response.data?.message || '请求失败')
        }
    )

    return customHttp
}

// ========== 错误处理示例 ==========

// 7. 完整的错误处理
export const exampleErrorHandling = async () => {
    try {
        const result = await http.get('/api/data')
        return result
    } catch (error) {
        // 根据错误类型进行不同处理
        if (error.code === 'NETWORK_ERROR') {
            console.error('网络连接失败')
            uni.showModal({
                title: '网络错误',
                content: '请检查网络连接后重试',
                showCancel: false
            })
        } else if (error.code === 401) {
            console.error('未授权访问')
            // 跳转到登录页
            uni.navigateTo({
                url: '/pages/login/login'
            })
        } else if (error.code === 0) {
            console.error('业务逻辑错误:', error.message)
            // 业务错误已经在拦截器中显示toast了
        } else {
            console.error('未知错误:', error)
            uni.showToast({
                title: '请求失败，请稍后重试',
                icon: 'none'
            })
        }
        throw error
    }
}

// ========== 并发请求示例 ==========

// 8. 并发请求
export const exampleConcurrentRequests = async () => {
    try {
        const [userInfo, userPosts, userFriends] = await Promise.all([
            http.get('/user/info'),
            http.get('/user/posts'),
            http.get('/user/friends')
        ])

        return {
            userInfo,
            userPosts,
            userFriends
        }
    } catch (error) {
        console.error('并发请求失败:', error)
        throw error
    }
}

// ========== 请求重试示例 ==========

// 9. 带重试机制的请求
export const exampleRetryRequest = async (url, maxRetries = 3) => {
    let lastError
    
    for (let i = 0; i < maxRetries; i++) {
        try {
            const result = await http.get(url)
            return result
        } catch (error) {
            lastError = error
            console.warn(`请求失败，第${i + 1}次重试:`, error.message)
            
            if (i < maxRetries - 1) {
                // 等待一段时间后重试
                await new Promise(resolve => setTimeout(resolve, 1000 * (i + 1)))
            }
        }
    }
    
    throw lastError
}